package OT.shoufouni.mainGUI;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import OT.shoufouni.R;
import OT.shoufouni.gpsMaps.findRoute;
import OT.shoufouni.serverThreads.serverLocateFriendQuaryThread;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class addFriendFrame extends ListActivity {
	
	private static final int RECEIVE_MESSAGE = 0;
	private static final int CREATE_LIST_ENTRY = 1;
    private static final String NAME = "NAME";
    private static final String ADDRESS = "ADDRESS";
    private static final String TEL = "TEL";
    private SimpleAdapter adapter;
	ArrayList<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
	ArrayList<Map<String, String>> newGroupData = new ArrayList<Map<String, String>>();
	private Handler mHandler = new Handler();
	
	String name,mail;
	
	private myContainer localDB = new myContainer(this);
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addfriend);
        // show friends from the added file
        buildListsFromFile();
        // show friends from the DB
        addFriendsFromDB();
        
        adapter = new SimpleAdapter(
	    		this,
	            groupData,
	            R.layout.child_list_entry,
	            new String[] { NAME, ADDRESS, TEL },
	            new int[] { R.id.textview_tel, R.id.textview_address, R.id.textview_name }
	    );
        setListAdapter(adapter);
        Button buttonAddEntry = (Button)findViewById(R.id.button_add);
		buttonAddEntry.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(addFriendFrame.this, EntryAddActivity.class);
				startActivityForResult(intent,CREATE_LIST_ENTRY );
				}
			});
    }
    // add entries from the file 
    private void buildListsFromFile(){
		InputStream inputStream = this.getResources().openRawResource(R.raw.phonebook);
   	  	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
   	  	try{
   	  		String line = "";
   	  		while ((line = bufferedReader.readLine()) != null) {
				String[] strings = line.split(",");
				String city = strings[0].trim();
				String name = strings[1].trim();
				String address = strings[2].trim();
				String tel = strings[3].trim();
				buildListsEntry(name, address, tel,false);
				Log.d("buildListsEntry from file",""+city);
	   	  	}  		
   	  	}catch(Exception e){
   	  		Log.e(getClass().getSimpleName(), "readInputFile problem");
		}
	}
    // add new entry
    private void buildListsEntry(String name, String address, String tel, Boolean newEntry){
    	Map<String, String> childMap = new HashMap<String, String>();
    	childMap.put(NAME, name);
		childMap.put(ADDRESS, address );
		childMap.put(TEL, tel );
		groupData.add(childMap);
		newGroupData.add(childMap);
		// if realy new, add to the DB
		if (true == newEntry){
			localDB.addNewFriendToDB(name, tel, address);
		}
	}
    
    private void writeEntriesToDB(ArrayList<Map<String, String>> newData){
    	localDB.addFriendsArrayToDB(newData);
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CREATE_LIST_ENTRY) {
			if (resultCode == RESULT_OK) {   
        	    String name    = data.getStringExtra("name"); 
        	    String address    = data.getStringExtra("address"); 
        	    String tel	= data.getStringExtra("tel");
       			buildListsEntry( name, address, tel,true);
			}
		}
	}
    public void onListItemClick(ListView parent, View v, final int position,long id) {
    	new AlertDialog.Builder(this)
        .setMessage("Do you want to locate\n "+groupData.get(position).get(NAME))
        .setTitle("Find friends in the area")
        .setCancelable(false)
        .setPositiveButton("yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
            	   Toast.makeText(addFriendFrame.this,"Connecting to the server"+"\nPlease wait",Toast.LENGTH_LONG).show();
            	   name = groupData.get(position).get(NAME);
            	   mail = groupData.get(position).get(ADDRESS);
            	   Context context = getApplicationContext();
            	   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                   String IdMail = prefs.getString("ID_MAIL", "");
            	   serverLocateFriendQuaryThread quaryThread = 
     	        	  new serverLocateFriendQuaryThread(addFriendFrame.this,mail,IdMail);
   		    		quaryThread.start();
               }
           })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
           })
         .show();
    }
    
    public void responseDisplay(final myLocation receivedData) {
    	// locate the chosen friend
    	mHandler.post(new Runnable() {
            public void run() {
            	if (null==receivedData){
            		Toast.makeText(addFriendFrame.this,"Connection failed or couldn't\nlocate the friend\nPlease try again",Toast.LENGTH_LONG).show();
            	}
            	else{
            		Intent intent = new Intent(addFriendFrame.this, findRoute.class);
            		intent.putExtra("locationX", receivedData.getX());
                    intent.putExtra("locationY", receivedData.getY());
                    intent.putExtra("name", name);
                    intent.putExtra("adress", mail);
                    startActivityForResult(intent,RECEIVE_MESSAGE);
            	}
             }
          });
    }
    
    private void addFriendsFromDB(){
    	Cursor cFriends = null;
    	cFriends = localDB.getFriendsReadableCursor();
    	if (null!=cFriends){
    		if  (cFriends.moveToFirst()) {
    			do {
    				Map<String, String> childMap = new HashMap<String, String>();
    		    	childMap.put(NAME, cFriends.getString(cFriends.getColumnIndex("Name")));
    				childMap.put(ADDRESS, cFriends.getString(cFriends.getColumnIndex("EmailId")));
    				childMap.put(TEL, cFriends.getString(cFriends.getColumnIndex("Tel")));
    				groupData.add(childMap);
    				newGroupData.add(childMap);
    			}while (cFriends.moveToNext());
    		} 
    	}
    	cFriends.close();
    }
    
}